package com.smartcommunity.controller.people;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.smartcommunity.api.engine.EngineApi;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.dao.people.PeopleDao;
import com.smartcommunity.entity.people.People;
import com.smartcommunity.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/inspection")
@Api(value = "健康检查")
@Slf4j
public class InspectionController {

    @Autowired
    private PeopleDao peopleDao;

    @Autowired
    private EngineApi engineApi;

    @ApiOperation(value = "实有人口无法置信问题检查")
    @GetMapping(path = "/whyPeopleCanNotBind")
    public ResponseEntity<Result> whyPeopleCanNotBind(@RequestParam String credentialNo, @RequestParam(required = false) String vid) {
        final List<String> credentials = new LinkedList<>();
        credentials.add(credentialNo);
        List<People> peopleList = peopleDao.getPeopleByCredentialNo(credentials);
        if (CollectionUtils.isEmpty(peopleList)) {
            return ResponseEntity.ok(Result.error(500, "实有人口无法在数据库中被检索到，请检查实有人口是否被删除"));
        } else {
            People people = peopleList.get(0);
            if (StringUtils.isEmpty(people.getIdCardPic())) {
                return ResponseEntity.ok(Result.error(500, "实有人口图片为空，请上传图片"));
            }
            if (StringUtils.isEmpty(people.getFeatureId())) {
                return ResponseEntity.ok(Result.error(500, "实有人口未同步到vid引擎常口库，请手动同步或者等待系统自动同步"));
            } else {
                if ("-1".equals(people.getFeatureId())) {
                    return ResponseEntity.ok(Result.error(500, "添加实有人口特征到vid引擎常口库失败,请检查vid引擎是否启动正常"));
                } else if ("-2".equals(people.getFeatureId())) {
                    try {
                        final URL url = new URL(people.getIdCardPic());
                        final URLConnection conn = url.openConnection();
                        final InputStream inStream = conn.getInputStream();
                        if (inStream.available() > 0) {
                            return ResponseEntity.ok(Result.error(500, "实有人口图片提取特征失败,请检查结构化引擎是否启动正常，或者图片大小，清晰度，是否包含人脸等"));
                        } else {
                            return ResponseEntity.ok(Result.error(500, "实有人口图片下载失败,请确认图片url是否正常，lis服务是否正常"));
                        }
                    } catch (IOException e) {
                        return ResponseEntity.ok(Result.error(500, "实有人口图片下载异常,请确认图片url是否正常，lis服务是否正常"));
                    }
                } else if ("0".equals(people.getFeatureId())) {
                    return ResponseEntity.ok(Result.error(500, "实有人口未同步到vid引擎常口库，请手动同步或者等待系统自动同步"));
                } else {
                    Result<String> result = engineApi.getFeatureByFeatureId(people.getFeatureId());
                    if (result.isOk() && StringUtils.isNotEmpty(result.getData())) {
                        Result vidResult = engineApi.getVidPersonsByIdCard(credentialNo);
                        if (vidResult.getData() != null) {
                            final List<Map<String, Object>> resultDataList = JSONArray.parseObject(vidResult.getData().toString(), List.class);
                            if (!CollectionUtils.isEmpty(resultDataList)) {
                                if (StringUtils.isEmpty(people.getVid())) {
                                    return ResponseEntity.ok(Result.error(500, "vid引擎可以通过身份证查询到vid,但是实有人口没有绑定vid,请排查base-service是否异常,base服务需要将vid同步到t_people表"));
                                } else {
                                    for (Map<String, Object> map : resultDataList) {
                                        String existVid = map.get("vid") == null ? "" : map.get("vid").toString();
                                        if (existVid.equals(people.getVid())) {
                                            return ResponseEntity.ok(Result.ok("已置信"));
                                        }
                                        if (existVid.equals(vid)) {
                                            return ResponseEntity.ok(Result.ok("已置信"));
                                        }
                                    }
                                    return ResponseEntity.ok(Result.error(500, "vid引擎可以通过身份证查询到vid,但是实有人口没有绑定vid,请排查base-service是否异常,base服务需要将vid同步到t_people表" + JSON.toJSON(resultDataList)));
                                }
                            }
                        }
                        Map<String, Object> param = new HashMap<>();
                        param.put("imageData", people.getIdCardPic());
                        param.put("threshold", 90D);
                        param.put("topN", 10);
                        Result<Map<String, Object>> mapResult = engineApi.searchVidsByUrl(param);
                        if (mapResult.isOk()) {
                            return ResponseEntity.ok(Result.error(500, "可以通过实有人口的特征查询到vid，但是没有置信，请检查vid引擎置信服务是否运行正常" + mapResult.getData().toString() + "或者等vid有新的人脸出现时在查看结果"));
                        }
                        return ResponseEntity.ok(Result.error(500, "vid引擎无法通过身份证查询到vid,因为" + mapResult.getResultMessage()));
                    } else {
                        return ResponseEntity.ok(Result.error(500, "实有人口已同步到vid引擎，但是vid引擎无法查询到特诊，请检查vid引擎实有人口添加接口，并重新同步"));
                    }
                }
            }
        }
    }
}
